<template>
	<div>
    <div v-if="articles.length === 0" class="article-preview">
      No articles are here... yet.
    </div>
    <div v-else
    	class="article-preview" 
    	v-for="(article, index) in articles"
      :article="article"
      :key="article.slug">
      <div class="article-meta">
      	<nuxt-link :to="{name: 'profile', params: { username: article.author.username }}">
        	<img :src="article.author.image" />
        </nuxt-link>
        <div class="info">
        	<nuxt-link :to="{name: 'profile', params: { username: article.author.username }}" class="author">
          	{{ article.author.username }}
          </nuxt-link>
          <span class="date">{{ article.createdAt|date('MMM DD, YYYY') }}</span>
        </div>
        <button class="btn btn-sm pull-xs-right"
		      @click="toggleFavorite(article)"
		      :class="{
		        'btn-primary': article.favorited,
		        'btn-outline-primary': !article.favorited
		      }"
		      :disabled="article.favoritedDisabled"
		      >
          <i class="ion-heart"></i> {{ article.favoritesCount }}
        </button>
      </div>
      <router-link :to="{name: 'article', params: { slug: article.slug } }" 
      	class="preview-link">
        <h1>{{ article.title }}</h1>
        <p>{{ article.description }}</p>
        <span>Read more...</span>
      </router-link>
      <ul class="tag-list">
		    <li
		      class="tag-default tag-pill tag-outline"
		      v-for="(tag, index) of article.tagList"
		      :key="index"
		    >
		      <span v-text="tag" />
		    </li>
		  </ul>
    </div>

    <pagination :total="total" :limit="limit" :page="page" @changePage="changePage" />
  </div>
</template>

<script>
  import Pagination from '@/components/Pagination'
  import { addFavorite, deleteFavorite } from '@/api/article'
  import { mapState } from 'vuex'

	export default {
		name: 'ArticleList',
		components: {
      Pagination
    },
		props: {
			articles: {
				type: Array,
				required: true,
				default: function() {
					return []
				}
			},
			total: Number,
			limit: {
				type: Number,
				default: 20,
			}
		},
		data () {
			return {
			}
		},
		computed: {
			...mapState(['user']),
			page() {
				return Number(this.$route.query.page) || 1
			}
		},
		methods: {
			async toggleFavorite(article) {
				if (!this.user) {
          this.$router.push({ name: 'register' })
          
          return
        }

		  	article.favoritedDisabled = true
        if (article.favorited) {
        	await deleteFavorite(article.slug)
          article.favorited = false
	        article.favoritesCount -= 1
        } else {
        	await addFavorite(article.slug)
          article.favorited = true
          article.favoritesCount += 1
        }
			  article.favoritedDisabled = false
			},
			changePage(page) {
				this.$emit('changePage', page)
			}
		}
	}
</script>